package binaryTree.LayerOrderTraversal;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
//二叉树的右视图
public class Basic199 {
        //层序遍历
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> resList = new ArrayList<List<Integer>>();
            LinkedList<TreeNode> queue = new LinkedList<>();
            if (root!=null){
                queue.offer(root);
            }
            while (!queue.isEmpty()){
                int size = queue.size();
                ArrayList<Integer> temp = new ArrayList<>();
                while (size>0){
                    TreeNode node = queue.poll();
                    size--;
                    temp.add(node.val);

                    if (node.left!=null){
                        queue.offer(node.left);
                    }
                    if (node.right!=null){
                        queue.offer(node.right);
                    }
                }
                resList.add(temp);
            }
            return  resList;
        }

    public List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> integers = new ArrayList<>();
        List<List<Integer>> list = levelOrder(root);
        for (List<Integer>  temp:
            list ) {
           integers.add(temp.get(temp.size()-1)) ;
        }

        return integers;
    }

    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();
        if (root == null) {
            return list;
        }
        que.offerLast(root);
        while (!que.isEmpty()) {
            int levelSize = que.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode poll = que.pollFirst();
                if (poll.left != null) {
                    que.addLast(poll.left);
                }
                if (poll.right != null) {
                    que.addLast(poll.right);
                }
                if (i == levelSize - 1) {
                    list.add(poll.val);
                }
            }
        }
        return list;
    }




    public static void main(String[] args) {
        TreeNode root= new TreeNode(5);
        TreeNode treeNode1 = new  TreeNode(3);
        TreeNode treeNode2=new TreeNode(1);
        TreeNode treeNode3 = new TreeNode(2);
        TreeNode treeNode4= new TreeNode(6);
        root.left=treeNode1;
        root.right=treeNode3;
        treeNode1.left=treeNode2;
        treeNode3.right=treeNode4;
        Basic199 basic199 = new Basic199();
        List<Integer> integers = basic199.rightSideView(root);
        for (int a:integers
             ) {
            System.out.println(a);
        }


    }

}
